package com.tanker.base.intercept;

import java.io.BufferedReader;
import java.io.InputStreamReader;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.fasterxml.jackson.databind.ObjectMapper;

public class MyInterceptor implements HandlerInterceptor {
	protected static ObjectMapper mapper = new ObjectMapper();
	private final static Logger logger = LoggerFactory.getLogger(MyInterceptor.class);
	
    public static final String key = "";
    public static final String security = "";

	@SuppressWarnings({ "rawtypes", "unchecked", "serial" })
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
        /*String res = IOUtils.toString(request.getInputStream(),"UTF-8");
        String sign = request.getHeader("sign");
        String mySign = MD5.encode(key+security+res,"UTF-8");
        if(!mySign.equals(sign)){
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(JSON.toJSONString(new HashMap(){{this.put("head",new ResponseHead(false,"-1","sign error"));}}));
            return false;
        }*/
		
		
//		System.out.println("nojonono");
//		String reqContent = this.getRequestContent(request);
//		Map<String, Object>	dataMap = mapper.readValue(reqContent, TreeMap.class);
//
//		if(!StringUtils.hasText(reqContent)){
//			//sendResponseContent(response, ErrorCode.PARAM_ERROR);
//			return false;
//		}
//		request.setAttribute("content", dataMap);
//     	request.setAttribute("content", reqContent);

		//return HandlerInterceptor.super.preHandle(request, response, handler);		//判断是否有输入内容 -----------------------------------------------------------------------------------------------------------------
		//String reqContent = this.getRequestContent(request);
//		if(!StringUtils.hasText(reqContent)){
//			sendResponseContent(response, ErrorCode.PARAM_ERROR);
//			return false;
//		}
//		Map<String, Object>	dataMap = mapper.readValue(reqContent, TreeMap.class);
//		String sign = (String) dataMap.remove("sign");
//    	//TreeMap<String, Object> treeMap = new TreeMap<String, Object>();
//    	//treeMap.putAll(data);
//		StringBuffer sbff = new StringBuffer();
//		
//		for(Map.Entry<String, Object> m: dataMap.entrySet()){
//			sbff.append(m.getKey()).append(m.getValue());
//    	}
//	
//    	String key = sbff.toString().toUpperCase() + "11111";
//    	logger.info("MD5转换字符："+key);
//    	String md5str = ApiUtils.md5Encode(key);
//    	logger.info("签名："+md5str);
//    	if(!md5str.equals(sign)){
//			return true;	
//		}else{
//			logger.info("验证签名没通过");
//			return false;	
//		}
		
		return true;	

	}
	
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		// TODO Auto-generated method stub
		HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
	}
	
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		// TODO Auto-generated method stub
		HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
	}
	
	protected String getRequestContent(HttpServletRequest request){
		StringBuilder sb = null;
		try {
			BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream(), "UTF-8"));
			String line = null;
			sb = new StringBuilder();
			while((line = br.readLine())!=null){
			    sb.append(line+"\n");
			}
		} catch (Exception e) {
			logger.error("",e);
		}
		
		if(sb != null){
			return sb.substring(0, sb.lastIndexOf("\n"));
		}
	    return null;
	}

}
